/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import Client.*;
/**
 *
 * @author manelv8
 */
public class ServerSocketTCP extends ServerSocket  implements InterfaceServerSocket{

   
   
    public ServerSocketTCP(int port) throws IOException {
        super(port);
        
    }

    public ServerSocketTCP() throws IOException {
    }

    @Override
    public void close(){
        try {
            super.close();
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketTCP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @Override
    public InterfaceClientSocket aceitar() {
        ClientSocketTCP clientSocket = null;
        try {
           
            Socket socket =  super.accept();
            clientSocket = new ClientSocketTCP(socket);
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketTCP.class.getName()).log(Level.SEVERE, null, ex);
        }
       return clientSocket;
    }

 

    @Override
    public void enviarMsg(String msg,InterfaceClientSocket clientSocket ) {
        ClientSocketTCP client = (ClientSocketTCP) clientSocket;   
        PrintStream writer = null;
        try {
            writer = new PrintStream(client.getSocket().getOutputStream());
            writer.println(msg);
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketTCP.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            writer.close();
        }
    }

    @Override
    public String receberMsg(InterfaceClientSocket clientSocket) {
          String linha = "";
           ClientSocketTCP client = (ClientSocketTCP) clientSocket;  
           
        try {
            
            BufferedReader rd = new BufferedReader(new InputStreamReader(client.getSocket().getInputStream()));
             linha = rd.readLine(); 
             return linha;
             
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketTCP.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return linha;
    }

    @Override
    public void fechar() {
        this.close();
    }

   
    
}
